package cn.goour.web.base.tools

import com.scientiamobile.wurfl.core.Device
import com.scientiamobile.wurfl.core.GeneralWURFLEngine
import com.scientiamobile.wurfl.core.updater.Frequency
import com.scientiamobile.wurfl.core.updater.UpdateResult
import com.scientiamobile.wurfl.core.updater.WURFLUpdater
import getUserAgent
import org.springframework.util.ClassUtils
import javax.servlet.ServletContext
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession


var wurfl: GeneralWURFLEngine? = null
var wurflUpdate: WURFLUpdater? = null

/**
 * 获得WURFL对象
 */
fun ServletContext.getWURFL(): GeneralWURFLEngine {
    val wurflKey = "_wurfl"
    if (wurfl == null) {
        synchronized(this) {
            if (wurfl == null) {
                val _wurfl: Any? = this.getAttribute(wurflKey)
                if (_wurfl is GeneralWURFLEngine) {
                    wurfl = _wurfl
                    return _wurfl
                }
                /**
                 * 这里是自定义配置时的代码，没有使用SpringBoot的自动注入
                 */
                log("对WURFL服务进行实例化")
                val wurflFile = ClassUtils.getDefaultClassLoader().getResource(getInitParameter("wurfl")).path
                log("WURFL服务文件加载路径：$wurflFile")
                wurfl = GeneralWURFLEngine(wurflFile)

                log("WURFL服务加载数据文件")
                wurfl!!.load()

                /**
                 * 下面是配置了自动注入时的代码
                 */
//                val wac = WebApplicationContextUtils.getWebApplicationContext(this)
//                wurfl = wac.getBean(GeneralWURFLEngine::class.java) as GeneralWURFLEngine

                /**
                 *
                 * 下面是使用servlet监听时的代码
                 */
//                wurfl = this.getAttribute(WURFLEngine::class.java.name) as GeneralWURFLEngine?

                this.setAttribute(wurflKey, wurfl)
            }
        }
    }

    log("WURFL获取成功")
    return wurfl!!
}

/**
 * 获得WURFL更行对象实例
 */
fun ServletContext.getWuflUpdate(): WURFLUpdater {
    log("正在获取WURFL更新对象")
    val wurflUpdateKey = "_wurflUpdate"
    if (wurflUpdate == null) {
        synchronized(this) {
            if (wurflUpdate == null) {
                val _updater: Any? = this.getAttribute(wurflUpdateKey)
                if (_updater is WURFLUpdater) {
                    wurflUpdate = _updater
                    return _updater
                }

                /**
                 * 下面是使用自定义配置时需要的代码，没有使用自动注入方式
                 */
                val wurfl = this.getWURFL()

                log("正在创建WURFL更新对象")
                val wurflUpdateUrl = this.getInitParameter("wurflUpdateUrl")
                log("WURFL更新数据的URL：$wurflUpdateUrl")

                wurflUpdate = WURFLUpdater(wurfl, wurflUpdateUrl)

                this.setAttribute(wurflUpdateKey, wurflUpdate)
            }
        }
    }

    return wurflUpdate!!
}

/**
 * 对WURFL启动定时更新功能
 */
fun ServletContext.wurflStartPeriodicUpdate() {
    log("对WURFL开启异步更新数据服务")
    val updater = this.getWuflUpdate()
    updater.setFrequency(Frequency.DAILY)
    updater.performPeriodicUpdate()
}

/**
 * 停止WURFL的停止更新服务
 */
fun ServletContext.wurflStopPeriodicUpdate() {
    log("对WURFL停止异步更新数据服务")
    val updater = this.getWuflUpdate()
    updater.stopPeriodicUpdate()
}

/**
 * 立即对WURFL进行更新
 */
@Throws(Exception::class)
fun ServletContext.wurflRunUpdate(): UpdateResult {
    log("对WURFL进行立即更新数据")
    val updater = this.getWuflUpdate()
    return updater.performUpdate()
}


/**
 * 获得当前访问者的设备信息，系统通过WURFL进行解析并提供此服务
 */
fun HttpServletRequest.getDevice(): Device {

    val obj1: Any? = this.session.getAttribute("device")
    if (obj1 is Device) {
        return obj1
    }

    val device = this.servletContext.getWURFL().getDeviceForRequest(this.getUserAgent())
    this.session.setAttribute("device", device)
    return device
}

fun HttpServletRequest.getDeviceBean(): DeviceBean {
    return DeviceBean(this.getDevice())
}

fun HttpSession.getDevice(): Device? {
    val obj1: Any? = this.getAttribute("device")
    if (obj1 is Device) {
        return obj1
    }
    return null
    /*val request = (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).request // 这里被抛弃使用，因为有可能是在没有任何HTTP请求的时候调用，到时这里会出现错误
    return request.getDevice()*/
}

class DeviceBean(var device: Device) {
    var is_app_webview: Boolean = false
        get() {
            return device.getVirtualCapability("is_app_webview").toBoolean()
        }
    var is_app: Boolean = false
        get() {
            return device.getVirtualCapability("is_app").toBoolean()
        }
    var is_mobile: Boolean = false
        get() {
            return device.getVirtualCapability("is_mobile").toBoolean()
        }
    var is_phone: Boolean = false
        get() {
            return device.getVirtualCapability("is_phone").toBoolean()
        }
    var advertised_app_name: String = ""
        get() {
            return device.getVirtualCapability("advertised_app_name").toString()
        }
    var is_full_desktop: Boolean = false
        get() {
            return device.getVirtualCapability("is_full_desktop").toBoolean()
        }
    var advertised_browser: String = ""
        get() {
            return device.getVirtualCapability("advertised_browser").toString()
        }
    var is_smartphone: Boolean = false
        get() {
            return device.getVirtualCapability("is_smartphone").toBoolean()
        }
    var is_robot: Boolean = false
        get() {
            return device.getVirtualCapability("is_robot").toBoolean()
        }
    var complete_device_name: String = ""
        get() {
            return device.getVirtualCapability("complete_device_name").toString()
        }
    var advertised_device_os: String = ""
        get() {
            return device.getVirtualCapability("advertised_device_os").toString()
        }
    var is_largescreen: Boolean = false
        get() {
            return device.getVirtualCapability("is_largescreen").toBoolean()
        }
    var is_android: Boolean = false
        get() {
            return device.getVirtualCapability("is_android").toBoolean()
        }
    var is_xhtmlmp_preferred: Boolean = false
        get() {
            return device.getVirtualCapability("is_xhtmlmp_preferred").toBoolean()
        }
    var device_name: String = ""
        get() {
            return device.getVirtualCapability("device_name").toString()
        }
    var advertised_browser_version: String = ""
        get() {
            return device.getVirtualCapability("advertised_browser_version").toString()
        }
    var is_html_preferred: Boolean = false
        get() {
            return device.getVirtualCapability("is_html_preferred").toBoolean()
        }
    var is_windows_phone: Boolean = false
        get() {
            return device.getVirtualCapability("is_windows_phone").toBoolean()
        }
    var is_ios: Boolean = false
        get() {
            return device.getVirtualCapability("is_ios").toBoolean()
        }
    var is_touchscreen: Boolean = false
        get() {
            return device.getVirtualCapability("is_touchscreen").toBoolean()
        }
    var is_wml_preferred: Boolean = false
        get() {
            return device.getVirtualCapability("is_wml_preferred").toBoolean()
        }
    var form_factor: String = ""
        get() {
            return device.getVirtualCapability("form_factor").toString()
        }
    var advertised_device_os_version: String = ""
        get() {
            return device.getVirtualCapability("advertised_device_os_version").toString()
        }

}